package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.*;
import com.py.credit.entity.common.InspectRule;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.common.TreeObj;
import com.py.credit.entity.enums.ContentTableFieldEnum;
import com.py.credit.entity.enums.ResourceContentPublishTableFieldEnum;
import com.py.credit.entity.enums.ResourceTableFieldsEnum;
import com.py.credit.entity.enums.TableRepeatCheckFieldsEnum;
import com.py.credit.service.*;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.MapCache;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.entity.SysUserEntity;
import com.py.framework.core.helper.HttpServletHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.RichTextString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 功能描述: 信息资源管理
 *
 * @author unknown
 * @date 19/3/29 13:57
 */
@RestController
@RequestMapping(value = "/content")
public class ContentController {

    private final static String FRONT_TABLE_ID = "content";

    private final static String FRONT_TABLE_SUBSCRIPTION_CONTENT_ID = "subscriptionContent";

    private final static String FRONT_TABLE_COMMON_CONTENT_ID = "commonContent";

    private final static int NUM_3 = 3;

    @Autowired
    private TableService tableService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private RemoteBaseService remoteBaseService;
    @Autowired
    private SharingMetricService SharingMetricService;
    @Autowired
    RuleBindingService ruleBindingService;

    @Value("${tableTitle}")
    private String tableTitle;

    @RequestMapping(value = "/getOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
        return new RestServiceResult<>(ResourceTableFieldsEnum.getOptionalColumns());
    }

    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
        return new RestServiceResult<>(ResourceTableFieldsEnum.getAdvancedConditionColumns());
    }

    /**
     * 功能描述: 获取所有资源目录排除公共的
     *
     * @param kId    资源库ID
     * @param deptId 部门ID
     * @param name   资源名称
     * @return List<Table> 资源目录
     * @author unknown
     * @date 19/3/29 13:56
     */
    @IgnoreAuthority
    @RequestMapping(value = "/getResources.json")
    public RestServiceResult<List<Table>> getResources(
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "deptId", defaultValue = "", required = true) String deptId,
            @RequestParam(value = "name", defaultValue = "", required = false) String name) {

        List<Table> tableList = tableService.getResources(kId, deptId, name);
        return new RestServiceResult<>(tableList);
    }

    /**
     * 功能描述: 获取资源表绑定字段规则
     *
     * @param tableId  资源ID
     * @param ruleName 规则名称
     * @param page     分页对象
     * @return List<InspectRule> 规则List
     * @author unknown
     * @date 19/3/29 13:55
     */
    @IgnoreAuthority
    @RequestMapping(value = "/getResourceColumnRules.json")
    public RestServiceResult<List<InspectRule>> getResourceColumnRules(
            @RequestParam(value = "tableId", defaultValue = "", required = true) String tableId,
            @RequestParam(value = "ruleName", defaultValue = "", required = false) String ruleName, Page page) {
        Integer version = ruleBindingService.selectCurrentContentVersion();
        List<InspectRule> ruleList = tableService.getResourceColumnRules(version, tableId, ruleName, page);
        return new RestServiceResult<>(page.getTotalCount(), ruleList);
    }

    /**
     * 功能描述: 获取资源表绑定表规则
     *
     * @param tableId  资源ID
     * @param ruleName 规则名称
     * @param page     分页信息
     * @return List<InspectRule> 规则List
     * @author unknown
     * @date 19/3/29 13:54
     */
    @IgnoreAuthority
    @RequestMapping(value = "/getResourceTableRules.json")
    public RestServiceResult<List<InspectRule>> getResourceTableRules(
            @RequestParam(value = "tableId", defaultValue = "", required = true) String tableId,
            @RequestParam(value = "ruleName", defaultValue = "", required = false) String ruleName, Page page) {
        Integer version = ruleBindingService.selectCurrentContentVersion();
        List<InspectRule> tableRules = tableService.getResourceTableRules(version, tableId, ruleName, page);
        return new RestServiceResult<>(page.getTotalCount(), tableRules);
    }

    /**
     * 功能描述: 获取资源List
     *
     * @param kId       资源库ID
     * @param type      资源类型
     * @param deptId    部门ID
     * @param condition 高级检索
     * @param page      分页
     * @return List 资源List
     * @author unknown
     * @date 19/3/29 14:06
     */
    @RequestMapping(value = "/getTableList.json")
    public RestServiceResult<List<Map<String, Object>>> getTableList(
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "type", defaultValue = "", required = true) String type,
            @RequestParam(value = "deptId", defaultValue = "", required = true) String deptId,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String[] configColumns = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID + "_" + type);
            } else {
                ExceptionLogger.error("ContentController#getTableList", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("ContentController#getTableList", "未获取到当前用户信息！");
        }

        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? ResourceTableFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        String[] additionalColumns = {"tableId", "deptId", "kId", "type", "information_type"};
        List<Map<String, Object>> tableList = tableService.getByConditionForPage(kId, deptId, type, showColumns,
                additionalColumns, condition, page);
        return new RestServiceResult<>(page.getTotalCount(), tableList);

    }

    @RequestMapping(value = "/addShowColunms.json")
    public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
                                                    @RequestParam(value = "type", defaultValue = "", required = true) String type, HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID + "_" + type, columns);
            } else {
                ExceptionLogger.error("ContentController#addShowColunms", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("ContentController#addShowColunms", "未获取到当前用户信息！");
        }
        return new RestServiceResult<>();
    }

    @RequestMapping(value = "/addBookContentShowColunms.json")
    public RestServiceResult<String> addBookContentShowColunms(
            @RequestParam(value = "columns", required = true) String[] columns, HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_SUBSCRIPTION_CONTENT_ID, columns);
            } else {
                ExceptionLogger.error("ContentController#addBookContentShowColunms", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("ContentController#addBookContentShowColunms", "未获取到当前用户信息！");
        }
        return new RestServiceResult<>();
    }

    /**
     * @api {post} /content/addCommonContentShowColunms.json 缓存公共目录信息展示列
     * @apiName addCommonContentShowColunms
     * @apiVersion 0.0.1
     * @apiGroup 资源目录管理
     * @apiParam {String[]} columns 列名 (必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":1,"data":null}
     */
    @RequestMapping(value = "/addCommonContentShowColunms.json")
    public RestServiceResult<String> addCommonContentShowColunms(
            @RequestParam(value = "columns", required = true) String[] columns, HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_COMMON_CONTENT_ID, columns);
            } else {
                ExceptionLogger.error("ContentController#addCommonContentShowColunms", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("ContentController#addCommonContentShowColunms", "未获取到当前用户信息！");
        }
        return new RestServiceResult<>();
    }

    /**
     * 功能描述:unknow
     *
     * @param condition 高级检索
     * @param page      分页
     * @return
     * @author unknow
     * @date 19/3/29 14:04
     */
    @RequestMapping(value = "/getBookcontentList.json")
    public RestServiceResult<List<Map<String, Object>>> getTableList(
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletRequest request) {
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                Long userArea = userInfo.getAreaId() == null ? 0 : userInfo.getAreaId();
                String[] configColumns = (String[]) MapCache.get(userArea + "_" + FRONT_TABLE_SUBSCRIPTION_CONTENT_ID);
                List<String> showColumns = (configColumns == null || configColumns.length == 0)
                        ? ContentTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
                List<Map<String, Object>> tableList = contentService.getBookContentListForPage(showColumns,
                        new String[]{"id", "checked","check_status","status"}, condition, page, userArea);
                result.setData(tableList);
                result.setCount(page.getTotalCount());
                return result;
            } else {
                result.setCode(user.getCode());
                result.setMsg("未获取到当前用户信息");
                ExceptionLogger.error("ContentController#getBookcontentList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg("未获取到当前用户信息");
            ExceptionLogger.error("ContentController#getBookcontentList", "未获取到当前用户信息！");
            return result;
        }
    }

    @RequestMapping(value = "/getCommonContentList.json")
    public RestServiceResult<List<Map<String, Object>>> getCommonContentList(
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String[] configColumns = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_COMMON_CONTENT_ID);
            } else {
                ExceptionLogger.error("ContentController#getCommonContentList", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("ContentController#getCommonContentList", "未获取到当前用户信息！");
        }
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? ResourceContentPublishTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        List<Map<String, Object>> tableList = contentService.getCommonContentListForPage(showColumns,
                new String[]{"id"}, condition, page);
        return new RestServiceResult<>(page.getTotalCount(), tableList);
    }

    @RequestMapping(value = "/getCommonContentOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getCommonContentOptionalColums() {
        return new RestServiceResult<>(ResourceContentPublishTableFieldEnum.getOptionalColumns());

    }

    @RequestMapping(value = "/getCommonContentAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getCommonContentAdvancedConditionColumns() {
        return new RestServiceResult<>(
                ResourceContentPublishTableFieldEnum.getAdvancedConditionColumns());
    }

    @RequestMapping(value = "/exportCommoncontentList.json")
    public void exportCommoncontentList(
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletResponse response) throws IOException {
        page.setLimit(1000);
        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        List<Map<String, Object>> tableList = contentService.getCommonContentListForPage(showColumns, null, condition,
                page);
        List<OptionalColumn> optionalColumns = ResourceContentPublishTableFieldEnum.getOptionalColumns();
        ExcelUtil.downloadExcel(response, tableList, "公共目录列表", "公共目录列表", showColumns, optionalColumns);

    }

    @RequestMapping(value = "/exportBookcontentList.json")
    public void exportBookcontentList(
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletResponse response) throws IOException {
        page.setLimit(1000);
        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        List<Map<String, Object>> tableList = contentService.getBookContentListForPage(showColumns, null, condition,
                page, 0);
        List<OptionalColumn> optionalColumns = ContentTableFieldEnum.getOptionalColumns();
        ExcelUtil.downloadExcel(response, tableList, "订阅目录列表", "订阅目录列表", showColumns, optionalColumns);
    }

    @RequestMapping(value = "/getBkContentOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getBkContentOptionalColums() {
        return new RestServiceResult<>(ContentTableFieldEnum.getOptionalColumns());
    }

    @RequestMapping(value = "/getBkContentAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getBookContentAdvancedConditionColumns() {
        return new RestServiceResult<>(ContentTableFieldEnum.getAdvancedConditionColumns());
    }

    @RequestMapping(value = "/export.json")
    public void export(@RequestParam(value = "kId", defaultValue = "", required = true) String kId,
                       @RequestParam(value = "deptId", defaultValue = "", required = true) String deptId,
                       @RequestParam(value = "type", defaultValue = "", required = true) String type,
                       @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
                       @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
                       HttpServletResponse response) throws IOException {
        page.setLimit(1000);
        List<String> columns = JSONArray.parseArray(columnEN, String.class);
        List<Map<String, Object>> data = tableService.getByConditionForPage(kId, deptId, type, columns, null, condition,
                page);
        List<OptionalColumn> optionalColumns = ResourceTableFieldsEnum.getOptionalColumns();
        ExcelUtil.downloadExcel(response, data, "信息资源", "信息资源", columns, optionalColumns);

    }

    @RequestMapping(value = "/addTable.json")
    public RestServiceResult<Object> addTable(
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "deptId", defaultValue = "", required = true) String deptId, Table table,
            @RequestParam(value = "column", defaultValue = "", required = true) String column,
            HttpServletRequest request) {
        String userName = null;
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                userName = userInfo.getUsername();
            }
        } else {
            ExceptionLogger.error("ContentController#addTable", "未获取到当前用户信息！");
        }
        table.setMaintainer(userName == null ? "" : userName);
        List<Column> columns = JSONArray.parseArray(column, Column.class);
        // 固定字段
        List<Column> sharingColumn = SharingMetricService.getSharingColumns(kId);
        if (CollectionUtils.isEmpty(sharingColumn)) {
            throw new ServiceException("主体库公共字段配置为空，先检查配置");
        }
        sharingColumn.addAll(columns);
        tableService.addTableInfo(kId, deptId, table, sharingColumn);
        return new RestServiceResult<>();
    }

    @RequestMapping(value = "/updateTable.json")
    public RestServiceResult<Object> updateTable(
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "deptId", defaultValue = "", required = true) String deptId, Table table,
            @RequestParam(value = "addColumn", defaultValue = "", required = true) String addColumn,
            @RequestParam(value = "delColumn", defaultValue = "", required = true) String delColumn,
            @RequestParam(value = "updateColumn", defaultValue = "", required = true) String updateColumn) {
        List<Column> addColumns = JSONArray.parseArray(addColumn, Column.class);
        List<Column> updateColumns = JSONArray.parseArray(updateColumn, Column.class);
        List<Column> delColumns = JSONArray.parseArray(delColumn, Column.class);
        tableService.updateTable(kId, deptId, table, addColumns, updateColumns, delColumns);
        return new RestServiceResult<>();
    }

    @RequestMapping(value = "/detail")
    public RestServiceResult<Map<String, Object>> detail(
            @RequestParam(value = "tableId", defaultValue = "", required = true) int tableId,
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "deptId", defaultValue = "", required = true) String deptId) {
        Map<String, Object> tableInfo = tableService.getTableInfo(kId, deptId, tableId);
        return new RestServiceResult<>(tableInfo);
    }

    @RequestMapping(value = "/del")
    public RestServiceResult<Map<String, Object>> del(
            @RequestParam(value = "ids", defaultValue = "", required = true) String ids,
            @RequestParam(value = "type", defaultValue = "", required = true) String type,
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "deptId", defaultValue = "", required = true) String deptId) {
        tableService.del(ids, type, kId, deptId);
        return new RestServiceResult<>();
    }

    @RequestMapping(value = "/getSerialNumber.json")
    public RestServiceResult<String> getSerialNumber(HttpServletRequest request) {
        RestServiceResult<String> result = new RestServiceResult<String>();
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("ContentController#getSerialNumber", "未获取到当前用户信息！");
                return result;
            }
            int serialNumbe = tableService.getAndSetMaxSerialNumberByDeptId(userInfo.getOfficeId());
            result.setData(new DecimalFormat("0000").format(serialNumbe).toString());
            return result;
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }

    }

    /**
     * @api {post} /content/addCommonContent.json 添加公共目录
     * @apiName addCommonContent
     * @apiVersion 0.0.1
     * @apiGroup 目录管理
     * @apiParam {String}name 公共目录名称 (必需)
     * @apiParam {String}description 公共目录描述 (必需)
     * @apiParam {String}useImmediately 是否立即启用 (必需)
     * @apiParam {String}nodes 共享目录节点 (必需)
     * @apiParam {String}type 共享目录类型 (必需)
     * @apiParamExample {json} 请求参数示例
     * {"name":"吉林公共目录v_1.0","description":"吉林公共目录v_1.0","useImmediately":"Y","nodes":[{"id":"100000","name":"法人库","type":"K","pId":"0","rootId":"100000"},{"id":"1","name":"信用中心","type":"D","code":"XYZX","pId":"100000","rootId":"100000"},{"id":"2","name":"企业基本信息","type":"T","code":"qyjbxx","pId":"1","rootId":"100000"}]]}
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */

    @RequestMapping(value = "/addCommonContent.json")
    public RestServiceResult<String> addCommonContent(SContentInfo sContentInfo,
                                                      @RequestParam(value = "name", defaultValue = "", required = true) String name,
                                                      @RequestParam(value = "description", defaultValue = "", required = true) String description,
                                                      @RequestParam(value = "useImmediately", defaultValue = "", required = true) String useImmediately,
                                                      @RequestParam(value = "nodes", defaultValue = "", required = true) String nodes,
                                                      HttpServletRequest request) {
    	System.out.println("name = "+name);
    	System.out.println("description = "+description);
    	System.out.println("sContentInfo = "+sContentInfo);
        if (StringUtils.isBlank(name) || StringUtils.isBlank(description)) {

            throw new ServiceException("版本名称和描述不得为空");

        }

        List<TreeObj> nodeList = JSONArray.parseArray(nodes, TreeObj.class);
        if (CollectionUtils.isEmpty(nodeList)) {
            throw new ServiceException("目录节点不能为空");
        }

        String userName = null;

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                userName = userInfo.getUsername();

            }

        } else {

            ExceptionLogger.error("ContentController#addCommonContent", "未获取到当前用户信息！");
        }

        sContentInfo.setMaintainer(userName == null ? "" : userName);

        contentService.addCommonContent(sContentInfo, nodeList);

        return new RestServiceResult<String>();

    }

    /**
     * @api {post} /content/commitCheck.json 提交审核
     * @apiName commitCheck
     * @apiVersion 0.0.1
     * @apiGroup 目录管理
     * @apiParam {String}id 目录id (必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */

    @RequestMapping(value = "/commitCheck.json")
    public RestServiceResult<String> commitCheck(
            @RequestParam(value = "id", defaultValue = "", required = true) String id, HttpServletRequest request) {
        Long userId = null;
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                userId = userInfo.getId();
            }
        } else {
            ExceptionLogger.error("ContentController#commitCheck", "未获取到当前用户信息！");
        }
        remoteBaseService.addWorkFlow("resourcePublish", UuidUtil.getInstance().getUUid(), String.valueOf(userId), null,
                id, "版本发布", "", "4", null);
        // 审核中
        contentService.checkCommonContent(id, "S");
        return new RestServiceResult<>();

    }

    /**
     * @api {get} /content/getCommonContentDetail.json 获取公共目录详情
     * @apiName getCommonContentDetail
     * @apiVersion 0.0.1
     * @apiGroup 目录管理
     * @apiParam {int}id 公共目录id (必需)
     * @apiSuccess {TreeObj} treeObject 目录节点
     * @apiSuccess {SContentInfo} info 目录信息
     * @apiSuccessExample {json} 成功返回结果 {"treeObject":0,"info":null}
     */

    @RequestMapping(value = "/getCommonContentDetail.json")
    public RestServiceResult<Map<String, Object>> getCommonContentDetail(
            @RequestParam(value = "id", defaultValue = "", required = true) int id) {
        Map<String, Object> map = new HashMap<String, Object>();

        SContentInfo si = contentService.getCommonContentInfo(id);

        List<TreeObj> contentTree = contentService.getCommonContentDetail(id);

        map.put("treeObject", contentTree);
        map.put("info", si);

        return new RestServiceResult<Map<String, Object>>(map);

    }

    /**
     * @api {post} /content/updateCommonContentStatus.json 启用公共目录
     * @apiName updateCommonContentStatus
     * @apiVersion 0.0.1
     * @apiGroup 目录管理
     * @apiParam {int}id 公共目录id (必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @RequestMapping(value = "/updateCommonContentStatus.json")
    public RestServiceResult<String> updateCommonContentStatus(
            @RequestParam(value = "status", defaultValue = "", required = true) String status,
            @RequestParam(value = "id", defaultValue = "", required = true) int id) {

        contentService.updateCommonContentStatus(status, id);
        return new RestServiceResult<String>();

    }

    // 订阅版本目录
    @RequestMapping(value = "/addBookContent.json")
    public RestServiceResult<Map<String, Object>> addBookContent(SContentInfo sContentInfo,
                                                                 @RequestParam(value = "nodes", defaultValue = "", required = true) String nodes,
                                                                 HttpServletRequest request) {
        // 描述
        if (StringUtils.isBlank(sContentInfo.getName()) || StringUtils.isBlank(sContentInfo.getDescription())) {
            throw new ServiceException("订阅版本名称和描述不得为空");
        }
        List<TreeObj> nodeList = JSONArray.parseArray(nodes, TreeObj.class);
        if (CollectionUtils.isEmpty(nodeList)) {
            throw new ServiceException("目录不能为空");
        }
        String userName = null;
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                userName = userInfo.getUsername();
            }
        } else {
            ExceptionLogger.error("ContentController#addBookContent", "未获取到当前用户信息！");
        }

        sContentInfo.setMaintainer(userName == null ? "" : userName);
        contentService.addBookCommonContent(sContentInfo, nodeList);
        return new RestServiceResult<>();

    }

    /**
     * 功能描述: 启用/停用 订阅目录
     *
     * @param id     订阅目录id
     * @param status 状态位
     * @return 修改结果
     * @author unknow
     * @date 19/3/29 14:12
     */
    @RequestMapping(value = "/updateBookContentStatus.json")
    public RestServiceResult<Map<String, Object>> updateBookContentStatus(
            @RequestParam(value = "id", defaultValue = "", required = true) String id,
            @RequestParam(value = "status", defaultValue = "", required = true) String status) {
        contentService.updateBookContentStatus(id, status);
        return new RestServiceResult<>();

    }

    // 更新订阅版本目錄
    @RequestMapping(value = "/updateBookContent.json")
    public RestServiceResult<Map<String, Object>> updateBookContent(SContentInfo sContentInfo,
                                                                    @RequestParam(value = "nodes", defaultValue = "", required = true) String nodes,
                                                                    HttpServletRequest request) {

        if (StringUtils.isBlank(sContentInfo.getName()) || StringUtils.isBlank(sContentInfo.getDescription())) {

            throw new ServiceException("订阅版本名称和描述不得为空");

        }

        List<TreeObj> nodeList = JSONArray.parseArray(nodes, TreeObj.class);
        if (CollectionUtils.isEmpty(nodeList)) {
            throw new ServiceException("目录不能为空");
        }

        String userName = null;

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                userName = userInfo.getUsername();
            }

        } else {

            ExceptionLogger.error("ContentController#updateBookContent", "未获取到当前用户信息！");
        }

        sContentInfo.setMaintainer(userName == null ? "" : userName);
        contentService.updateBookContent(sContentInfo, nodeList);

        return new RestServiceResult<Map<String, Object>>();

    }

    // 更新订阅版本目录树
    @RequestMapping(value = "/editBookContentTree.json")
    public RestServiceResult<Map<String, Object>> editBookContentTree(
            @RequestParam(value = "id", defaultValue = "", required = true) int id) {
        Map<String, Object> map = new HashMap<String, Object>();

        SContentInfo si = contentService.getBookContentInfo(id);

        // 当前订阅版本目录

        List<TreeObj> boookContentTree = contentService.getBoookContentDetail(id);

        // 当前订阅版本目录依赖的公共目录
        List<TreeObj> commonContentTree = contentService.getCommonContentTree(si.getpVersion());

        buildCheck(commonContentTree, boookContentTree);

        map.put("treeObject", commonContentTree);
        map.put("info", si);

        return new RestServiceResult<Map<String, Object>>(map);

    }

    // 更新公共版本目录树
    @RequestMapping(value = "/editCommonContentTree.json")
    public RestServiceResult<Map<String, Object>> editCommonContentTree(
            @RequestParam(value = "id", defaultValue = "", required = true) int id) {
        Map<String, Object> map = new HashMap<String, Object>();

        SContentInfo si = contentService.getCommonContentInfo(id);

        List<TreeObj> originalContentTree = contentService.getOriginalContentTree();

        List<TreeObj> commonContentTree = contentService.getCommonContentTree(id);

        buildCheck(originalContentTree, commonContentTree);

        map.put("treeObject", originalContentTree);
        map.put("info", si);

        return new RestServiceResult<Map<String, Object>>(map);

    }

    /**
     * @param originalContentTree
     * @param commonContentTree
     */
    private void buildCheck(List<TreeObj> originalContentTree, List<TreeObj> commonContentTree) {
        for (TreeObj commonContentTreeNode : commonContentTree) {

            for (TreeObj originalContentTreeNode : originalContentTree) {
                if (commonContentTreeNode.getId() != null && commonContentTreeNode.getType() != null
                        && commonContentTreeNode.getpId() != null
                        && commonContentTreeNode.getType().equals(originalContentTreeNode.getType())
                        && commonContentTreeNode.getId().equals(originalContentTreeNode.getId())
                        && commonContentTreeNode.getpId().equals(originalContentTreeNode.getpId())) {

                    originalContentTreeNode.setChecked("true");

                }

            }

        }

    }

    // 更新公共版本目录
    @RequestMapping(value = "/updateCommonContent.json")
    public RestServiceResult<Map<String, Object>> updateCommonContent(SContentInfo sContentInfo,
                                                                      @RequestParam(value = "nodes", defaultValue = "", required = true) String nodes,
                                                                      HttpServletRequest request) {

        if (StringUtils.isBlank(sContentInfo.getName()) || StringUtils.isBlank(sContentInfo.getDescription())) {

            throw new ServiceException("版本名称和描述不得为空");

        }

        List<TreeObj> nodeList = JSONArray.parseArray(nodes, TreeObj.class);
        if (CollectionUtils.isEmpty(nodeList)) {
            throw new ServiceException("目录不能为空");
        }

        String userName = null;

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                userName = userInfo.getUsername();
            }

        } else {

            ExceptionLogger.error("ContentController#updateCommonContent", "未获取到当前用户信息！");
        }

        sContentInfo.setMaintainer(userName == null ? "" : userName);
        contentService.updateCommonContent(sContentInfo, nodeList);

        return new RestServiceResult<Map<String, Object>>();

    }

    // 删除公共版本
    @RequestMapping(value = "/delCommonContent.json")
    public RestServiceResult<Map<String, Object>> delCommonContent(
            @RequestParam(value = "ids", defaultValue = "", required = true) String ids) {

        contentService.delCommonContent(ids);

        return new RestServiceResult<Map<String, Object>>();

    }

    // 审核公共版本
    @RequestMapping(value = "/checkCommonContent.json")
    public RestServiceResult<String> checkCommonContent(
            @RequestParam(value = "id", defaultValue = "", required = true) String id,
            @RequestParam(value = "checkStatus", defaultValue = "W", required = true) String checkStatus) {

        contentService.checkCommonContent(id, checkStatus);

        return new RestServiceResult<String>();

    }

    // 订阅版本目录详情
    @RequestMapping(value = "/getBookContentDetail.json")
    public RestServiceResult<Map<String, Object>> getBookContentDetail(
            @RequestParam(value = "id", defaultValue = "", required = true) int id) {
        Map<String, Object> map = new HashMap<String, Object>();

        SContentInfo si = contentService.getBookContentInfo(id);

        List<TreeObj> boookContentTree = contentService.getBoookContentDetail(id);

        map.put("treeObject", boookContentTree);
        map.put("info", si);

        return new RestServiceResult<Map<String, Object>>(map);

    }

    // 删除订阅版本目錄
    @RequestMapping(value = "/delBookContent.json")
    public RestServiceResult<Map<String, Object>> delBookContent(
            @RequestParam(value = "ids", defaultValue = "", required = true) String ids) {

        contentService.delBookContent(ids);

        return new RestServiceResult<Map<String, Object>>();

    }

    // 根据订阅目录获取导入模板
    @RequestMapping(value = "/getTemplate.json")
    public RestServiceResult<Object> getTemplate(
            @RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId,
            @RequestParam(value = "contentId", defaultValue = "", required = true) Integer contentId,
            HttpServletResponse response, HttpServletRequest request) throws IOException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#getTemplate", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        // 获取顶级部门ID
        Long topDeptId = userInfo.getOfficeId();
        String pIds = userInfo.getAllParentId();
        if (StringUtils.isNotBlank(pIds)) {
            String t = StringUtils.split(pIds, ",")[0];
            topDeptId = StringUtils.isNoneBlank(t) ? Long.valueOf(t) : topDeptId;
        }
        try {
            String tipId = tableId + "_" + topDeptId;
            TableResult table = contentService.getTableColumns(tableId, contentId, tipId);
            String fileName = "";
            if (210000 == tableId) {
                fileName = "行政许可.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210001 == tableId) {
                fileName = "行政处罚.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210089 == tableId) {
                fileName = "行政强制.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210113 == tableId) {
                fileName = "行政征收.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            }else if (210122 == tableId) {
                fileName = "行政裁决.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210123 == tableId) {
                fileName = "行政确认.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210124 == tableId) {
                fileName = "行政给付.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210125 == tableId) {
                fileName = "行政奖励.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210126 == tableId) {
                fileName = "其他行政管理.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210212 == tableId) {
                fileName = "监督检查.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210309 == tableId) {
                fileName = "信用承诺.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210310 == tableId) {
                fileName = "抽查结果.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            } else if (210311 == tableId) {
                fileName = "抽查任务.xls";
                FileUtils.downloadFile(this.getClass().getResource("/" + fileName).getPath(), response);
            }   else {
                ExcelUtil.downloadTemplate(response, table);
            }
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("下载模板异常，请稍后再试！");
            ExceptionLogger.error("ContentController#getTemplate", "下载模板异常！ERROR:" + e.getMessage(), e);
            return result;
        }
    }
    // 门户网站根据订阅目录获取导入模板
    @IgnoreAuthority
    @RequestMapping(value = "/WebgetTemplate.json")
    public RestServiceResult<String> WebgetTemplate(           
    		
             @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
            HttpServletResponse response, HttpServletRequest request) throws IOException {
        RestServiceResult<String> result = new RestServiceResult<String>();
   	 Map<String, String>  parseObject = JSONObject.parseObject(condition, Map.class);
       Integer tableId = Integer.valueOf(parseObject.get("tableId"));
      Integer contentId = Integer.valueOf(parseObject.get("contentId"));
      Integer topDeptId = Integer.valueOf(parseObject.get("topDeptId"));
        try {
        	 String tipId = tableId + "_" + topDeptId;
            TableResult table = contentService.getTableColumns(tableId, contentId, tipId);
            if(table==null) {
            	result.setData("下载失败");
            	return result;
            }
            String fileName = "";
         
            	response.setContentType("application/vnd.ms-excel");
        		HSSFWorkbook workbook = null;
        		OutputStream fOut = null;
        		// 进行转码，使其支持中文文件名
        		String fileNanme = URLEncoder.encode(table.getTableNameCN(), "UTF-8");
        		response.setHeader("content-disposition", "attachment;filename=" + fileNanme + ".xls");
        		// 产生工作簿对象
        		workbook = new HSSFWorkbook();
        		// 产生工作表对象
        		HSSFSheet sheet = workbook.createSheet();
        		//得到一个poi工具
        		CreationHelper factory = workbook.getCreationHelper();  
        				// 得到换图对象
        		Drawing drawing = sheet.createDrawingPatriarch(); 
        				//设置注释位置
        		ClientAnchor anchor = factory.createClientAnchor(); 
        		workbook.setSheetName(0, table.getTableNameCN());
        		HSSFFont headfont = workbook.createFont();
        		headfont.setFontName("宋体");
        		headfont.setFontHeightInPoints((short) 13);// 字体大小
        		headfont.setBold(true);
        		HSSFCellStyle headstyle = workbook.createCellStyle();
        		headstyle.setFont(headfont);
        		headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        		headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        		headstyle.setLocked(true);
        		// headstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        		// headstyle.setFillBackgroundColor(HSSFColor.GREY_40_PERCENT.index);
        		// headstyle.setLeftBorderColor(HSSFColor.BLACK.index);

        		HSSFRow row = null;
        		HSSFCell cell = null;
        		row = sheet.createRow(0);

        		if (!CollectionUtils.isEmpty(table.getColumns())) {
        			for (int i = 0; i < table.getColumns().size(); i++) {
        				sheet.setColumnWidth(i, 8000);
        				cell = row.createCell(i);
        				cell.setCellStyle(headstyle);
        				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        				cell.setCellValue(table.getColumns().get(i).getMetricName());
        				Comment comment = drawing.createCellComment(anchor);  
        			    RichTextString str = factory.createRichTextString(table.getColumns().get(i).getTips());  
        			    comment.setString(str);  
//        			    comment.setAuthor("Apache POI");  
        			    cell.setCellComment(comment);  
        			}
        		}
        		ByteArrayOutputStream bos = new ByteArrayOutputStream();      		
        		workbook.write(bos);
        		workbook.close();
        		byte[] bytes = bos.toByteArray();
        		String  reString=Base64.getEncoder().encodeToString(bytes);
        		result.setData(reString);
           
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("下载模板异常，请稍后再试！");
            ExceptionLogger.error("ContentController#getTemplate", "下载模板异常！ERROR:" + e.getMessage(), e);
            return result;
        }
    }
    // 可订阅目录信息
    @RequestMapping(value = "/getSubscriptionInfo.json")
    public RestServiceResult<List<Map<String, Object>>> getSubscriptionInfo(
            @RequestParam(value = "id", defaultValue = "", required = true) String id, HttpServletRequest request) {

        List<Map<String, Object>> infos = contentService.getSubscriptionInfo(id);

        Set<Integer> ids = new HashSet<Integer>();

        for (Map<String, Object> info : infos) {
            Object subscriberId = info.get("subscriberId");
            if (subscriberId != null && subscriberId instanceof Integer) {
                ids.add((Integer) subscriberId);
            }

        }

        RestServiceResult<List<SysUserEntity>> users = remoteBaseService.getUsersByIds(ids,
                HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == users.getCode()) {

            List<SysUserEntity> data = users.getData();

            if (null != data) {

                for (Map<String, Object> info : infos) {

                    Object subscriberId = info.get("subscriberId");

                    for (SysUserEntity user : data) {

                        if (subscriberId != null && subscriberId instanceof Integer
                                && user.getId() == (Integer) subscriberId) {

                            info.put("subscriber", user.getRealName());

                        }

                    }

                }

            } else {

                ExceptionLogger.error("ContentController#getSubscriptionInfo", "获取用户信息失败！");

            }

        } else {

            ExceptionLogger.error("ContentController#getSubscriptionInfo", "获取用户信息失败！");
        }

        return new RestServiceResult<List<Map<String, Object>>>(infos);

    }

    // 获取已启用公共目录的树状图数据
    @RequestMapping(value = "/getTree.json")
    public RestServiceResult<Map<String, Object>> getCommonContentTree() {

        List<TreeObj> nodes = contentService.getCommonContentTree();

        Map<String, Object> map = new HashMap<String, Object>();

        if (!CollectionUtils.isEmpty(nodes)) {

            map.put("pVersion", nodes.get(0).getExtend());

        }

        map.put("data", nodes);

        return new RestServiceResult<Map<String, Object>>(map);

    }

    // 获取维护目录树狀图数据
    @RequestMapping(value = "/getOriginalContentTree.json")
    public RestServiceResult<List<TreeObj>> getOriginalContentTree() {

        return new RestServiceResult<List<TreeObj>>(contentService.getOriginalContentTree());

    }

    // 订阅目录

    @RequestMapping(value = "/bookContent.json")
    public RestServiceResult<String> bookContent(
            @RequestParam(value = "contentId", defaultValue = "", required = true) int contentId,
            HttpServletRequest request) {
        RestServiceResult<String> result = new RestServiceResult<String>();
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("ContentController#bookContent", "未获取到当前用户信息！");
                return result;
            }
            List<AreaEntity> areaList = contentService.getAllArea();
           
            for(AreaEntity area : areaList) {
            	 contentService.bookContent(area.getId(), contentId, userInfo.getId(), userInfo.getOfficeId());

            }
           
            return result;

        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;

        }

    }

    /**
     * 启用的公共目录树状图数据,可根据数据库节点和表属性筛选
     *
     * @param contentId
     * @return
     */
    @RequestMapping(value = "/getCommonContentTree.json")
    public RestServiceResult<Map<String, Object>> getCommentConentTree(
            @RequestParam(value = "rootId", defaultValue = "", required = true) String rootId,
            @RequestParam(value = "sharingType", defaultValue = "", required = true) String sharingType,
            @RequestParam(value = "informationType", defaultValue = "", required = true) String informationType) {

        SContentInfo sf = contentService.getCommonContentInfo();

        Map<String, Object> map = new HashMap<String, Object>();

        List<TreeObj> commonContentTree = contentService.getCommonContentTree(rootId, sharingType, informationType);

        map.put("commonContentId", sf.getId());

        map.put("data", commonContentTree);

        return new RestServiceResult<Map<String, Object>>(map);

    }

    /**
     * @api {get} /content/getepeatCheckOptionalColums.json 表是否验重信息资源列头
     * @apiName getepeatCheckOptionalColums
     * @apiVersion 0.0.1
     * @apiGroup 目录管理
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {String} result
     * @apiSuccessExample {json} 成功返回结果 {}
     */
    @RequestMapping(value = "/getepeatCheckOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getepeatCheckOptionalColums() {
        return new RestServiceResult<List<OptionalColumn>>(TableRepeatCheckFieldsEnum.getOptionalColumns());
    }

    /**
     * @api {get} /content/repeatCheckList.json 表是否验重信息资源接口
     * @apiName repeatCheckList
     * @apiVersion 0.0.1
     * @apiGroup 目录管理
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {Integer} deptId 部门ID
     * @apiSuccess {Integer} kId 库ID
     * @apiSuccess {Integer} resource_id 信息资源标识符
     * @apiSuccess {String} resource_title 信息资源名称
     * @apiSuccess {String} sharing_type 公开属性 P:社会公开,S:政务共享,A:授权查询
     * @apiSuccess {String} update_frequency 更新频率 S:实时，D:每日,W:每周,M:每月,Q:每季度,Y:每年
     * @apiSuccess {String} management_style 管理方式,M:手动，A:计算机处理
     * @apiSuccess {String} maintainer 维护人
     * @apiSuccess {Date} update_time 更新时间
     * @apiSuccess {String} repeatCheck 重复性校验 Y:校验(默认) N:不校验
     * @apiSuccess {Integer} tableId 表ID
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":135,"data":[{"tableId":200277,"deptId":1,"kId":100000,"resource_id":"10000060922","resource_title":"监督检查信息","sharing_type":"A","update_frequency":"D","management_style":"A","maintainer":"admin","update_time":1536568185000,"repeatCheck":"N"},{"tableId":200278,"deptId":1,"kId":100000,"resource_id":"10000060923","resource_title":"行政奖励信息","sharing_type":"A","update_frequency":"D","management_style":"A","maintainer":"superadmin","update_time":1523850995000,"repeatCheck":"Y"}]}
     */
    @RequestMapping(value = "/repeatCheckList.json")
    public RestServiceResult<List<Map<String, Object>>> repeatCheckList(HttpServletRequest request,
                                                                        @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page) {
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
        // 无自定义列，使用默认字段输出
        List<String> showColumns = TableRepeatCheckFieldsEnum.getDefaultShowColumnEN();
        // 添加不显示的字段
        String[] additionalColumns = {"tableId", "deptId", "kId"};
        try {
            List<Map<String, Object>> tableList = tableService.getByConditionForPage(null, null, null, showColumns,
                    additionalColumns, condition, page);
            result.setCount(page.getTotalCount());
            result.setData(tableList);
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("ContentController#repeatCheckList", "信息资源表验重列表查询异常！ERROR：" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("信息资源表验重查询异常!");
            return result;
        }
    }

    /**
     * @api {get} /content/repeatCheck.json 验重开关
     * @apiName repeatCheck
     * @apiVersion 0.0.1
     * @apiGroup 目录管理
     * @apiParam {String} repeatCheck 是否验重 Y:是 N:否
     * @apiParam {Integer} id 记录表ID
     * @apiParamExample {json} 请求参数示例 {"repeatCheck":"Y","id":1}
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {String} result
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @RequestMapping(value = "/repeatCheck.json")
    public RestServiceResult<Object> repeatCheck(HttpServletRequest request,
                                                 @RequestParam(value = "repeatCheck", defaultValue = "Y", required = true) String repeatCheck,
                                                 @RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
        RestServiceResult<Object> result = new RestServiceResult<>();
        // 远程获取用户信息
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("ContentController#repeatCheck", "未获取到当前用户信息！");
                return result;
            }
            // 只有管理员才能进行验重配置
            if (NUM_3 != userInfo.getUserType()) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("权限不足，只有管理员才能进行此操作！");
                return result;
            }
            try {
                tableService.updateRepeatCheck(repeatCheck, userInfo, id);
                return result;
            } catch (Exception e) {
                ExceptionLogger.error("ContentController#repeatCheck", "信息资源表验更新验重状态异常！ERROR：" + e.getMessage(), e);
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("信息资源表验更新验重状态异常!");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
    }

    // 根据订阅目录获取导入模板
    @IgnoreAuthority
    @RequestMapping(value = "/getExcel.json")
    public RestServiceResult<Object> getExcel(
            @RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId,
            @RequestParam(value = "title", defaultValue = "", required = true) String title,
            HttpServletResponse response, HttpServletRequest request) throws IOException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();
        try {
            TableResult table = contentService.getExcel(tableId, title);
            // table.setTableNameCN(title);
            table.setkId(tableId + "_1");
            ExcelUtil.downloadTemplate(response, table);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("下载模板异常，请稍后再试！");
            ExceptionLogger.error("ContentController#getTemplate", "下载模板异常！ERROR:" + e.getMessage(), e);
            return result;
        }
    }

    /**
     * @api {get} /content/getTableInfo.json 验重开关
     * @apiName getTableInfo
     * @apiVersion 0.0.1
     * @apiGroup 目录管理
     * @apiParam {List<Integer>} ids 是否验重 Y:是 N:否
     * @apiParam {Integer} rootId 记录表ID
     * @apiParamExample {json} 请求参数示例 {"ids":[210035,210013],"rootId":100000}
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {String} result
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @SuppressWarnings("unchecked")
    @IgnoreAuthority
    @RequestMapping(value = "/getTableInfo.json")
    public RestServiceResult<Object> getTableInfo(@RequestParam(value = "ids", defaultValue = "") List<Integer> ids,
                                                  @RequestParam(value = "rootId", defaultValue = "") Integer rootId, HttpServletResponse response,
                                                  HttpServletRequest request) throws IOException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();
        if (ids.size() == 0) {
            ids = null;
        }
        try {
            List<LinkedHashMap> selectTableInfo = tableService.selectTableInfo(ids, rootId);
            for (int i = 0; i < selectTableInfo.size(); i++) {
                String value = (String) selectTableInfo.get(i).get("resource_id");
                selectTableInfo.get(i).put("resource_id", tableTitle + value);
            }
            result.setData(selectTableInfo);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("下载模板异常，请稍后再试！");
            ExceptionLogger.error("ContentController#getTemplate", "下载模板异常！ERROR:" + e.getMessage(), e);
            return result;
        }
    }
}
